Build a Signature Pad in HTML, CSS, JS & Canvas | 您所在的位置:网站首页 › canvas ie › Build a Signature Pad in HTML, CSS, JS & Canvas |
Perfect! As next step we can setup the event listeners to interact with the pad. We will need to listen to pointerdown, pointerup and pointermove the pointerdown will be in charge to set the writing mode to true, the pointerup will be in charge to set the writing mode to false canvas.addEventListener('pointerdown', handlePointerDown, {passive: true});canvas.addEventListener('pointerup', handlePointerUp, {passive: true});canvas.addEventListener('pointermove', handlePointerMove, {passive: true});now let’s implement the handlers handlePointerDown const handlePointerDown = (event) => { writingMode = true; ctx.beginPath(); const [positionX, positionY] = getCursorPosition(event); ctx.moveTo(positionX, positionY);}handlePointerUp const handlePointerUp = () => { writingMode = false;}handlePointerMove const handlePointerMove = (event) => { if (!writingMode) return const [positionX, positionY] = getCursorPosition(event); ctx.lineTo(positionX, positionY); ctx.stroke();}where getCursorPosition is: const getCursorPosition = (event) => { positionX = event.clientX - event.target.getBoundingClientRect().x; positionY = event.clientY - event.target.getBoundingClientRect().y; return [positionX, positionY];}then lets set a couple of properties on our canvas context to style the drawing line: ctx.lineWidth = 3;ctx.lineJoin = ctx.lineCap = 'round';We are almost there, the last thing to add is the functionality to clear the canvas and the one for submit the form. NOTE: in this example we are not sending the data to the server so just for demonstration I’m going to generate an image and append it to the DOM form.addEventListener('submit', (event) => { event.preventDefault(); const imageURL = canvas.toDataURL(); const image = document.createElement('img'); image.src = imageURL; image.height = canvas.height; image.width = canvas.width; image.style.display = 'block'; form.appendChild(image); clearPad();})const clearPad = () => { ctx.clearRect(0, 0, canvas.width, canvas.height);}clearButton.addEventListener('click', (event) => { event.preventDefault(); clearPad();})That’s it! the final result should look like this Thanks for reading and I will see you in the next article :) have a nice day and happy coding! |
CopyRight 2018-2019 实验室设备网 版权所有 |